<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import {computed, ref, reactive, shallowRef, onBeforeUnmount, watch} from "vue";

import {
  ReformMainPageResponse,
  SirReformDetailEntity,  // 导入整改详情实体类型
  getReformDetailApi      // 导入获取整改详情接口
} from "@/api/airport/reform/reformMain";

import { ElMessage, ElRow, ElCol } from "element-plus";
import { Editor } from "@wangeditor/editor-for-vue";

import {
  viewEditorConfig,
  decodeBase64,
} from "@/api/airport/inspection/inspection";

import '@wangeditor/editor/dist/css/style.css'

interface Props {
  modelValue: boolean;
  row?: ReformMainPageResponse;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

// 计算属性用于安全地绑定和显示表单字段
const code = computed(() => props.row?.code || '');
const problemSource = computed(() => props.row?.problemSource || '');
const problemDetail = computed(() => props.row?.problemDetail || '');
const basis = computed(() => props.row?.basis || '');
const reformRequirement = computed(() => props.row?.reformRequirement || '');
const checkDate = computed(() => props.row?.checkDate || '');
const requestFeedbackDate = computed(() => props.row?.requestFeedbackDate || '');
const correctiveDeadline = computed(() => props.row?.correctiveDeadline || '');
const inspectors = computed(() => props.row?.inspectors || '');
const issueDeptName = computed(() => props.row?.issueDeptName || '');
const dutyDeptName = computed(() => props.row?.dutyDeptName || '');
const directCause = computed(() => props.row?.directCause || '');
const rootCause = computed(() => props.row?.rootCause || '');
const correctiveAction = computed(() => props.row?.correctiveAction || '');
const precautionAction = computed(() => props.row?.precautionAction || '');
const actionMakerName = computed(() => props.row?.actionMakerName || '');
const actionMakeTime = computed(() => props.row?.actionMakeTime || '');
const actionEvalerName = computed(() => props.row?.actionEvalerName || '');
const actionEvalTime = computed(() => props.row?.actionEvalTime || '');
const actionEval = computed(() => props.row?.actionEval || '');
const proofEvalerName = computed(() => props.row?.proofEvalerName || '');
const proofEvalTime = computed(() => props.row?.proofEvalTime || '');
const rectificationOpinion = computed(() => props.row?.rectificationOpinion || '');
const rectificationResult = computed(() => props.row?.rectificationResult || '未进行审核');

// 整改详情数据和加载状态
const reformDetail = ref<SirReformDetailEntity | null>(null);
const detailLoading = ref(false);

// 管理所有只读编辑器实例
const viewEditorRefs = ref<any[]>([]);

const handleViewEditorCreated = (editor: any) => {
  viewEditorRefs.value.push(editor);
};

// 监听弹窗显示状态，用于获取整改详情
watch(() => visible.value, async (newVal) => {
  const status = props.row?.reformStatus;
  const reformId = props.row?.reformId;

  if (newVal && reformId && ['2', '4', '6', '7'].includes(status)) {
    // 调用接口获取整改详情
    detailLoading.value = true;
    try {
      const { data } = await getReformDetailApi(reformId);

      // 对富文本内容进行解码处理
      if (data.correctiveActionProof) {
        data.correctiveActionProof = decodeBase64(data.correctiveActionProof);
      }
      if (data.precautionActionProof) {
        data.precautionActionProof = decodeBase64(data.precautionActionProof);
      }
      if (data.oldCorrectiveActionProof) {
        data.oldCorrectiveActionProof = decodeBase64(data.oldCorrectiveActionProof);
      }
      if (data.oldPrecautionActionProof) {
        data.oldPrecautionActionProof = decodeBase64(data.oldPrecautionActionProof);
      }
      reformDetail.value = data;
    } catch (error) {
      ElMessage.error('获取整改详情失败');
      console.error('获取整改详情失败', error);
    } finally {
      detailLoading.value = false;
    }
  }

  // 弹窗关闭时清空数据
  if (!newVal) {
    reformDetail.value = null;
  }
});

// 组件销毁时，销毁所有编辑器实例
onBeforeUnmount(() => {
  viewEditorRefs.value.forEach(editor => {
    if (editor) {
      editor.destroy();
    }
  });
  viewEditorRefs.value = [];
});

</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    title="整改通知书详情"
    v-model="visible"
    @confirm="visible = false"
    @cancel="visible = false"
  >
    <el-form label-width="180px">
      <div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="整改通知书编号：">
              <span>{{ code }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="问题来源：">
              <span>{{ problemSource }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检查日期：">
              <span>{{ checkDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交整改期限：">
              <span>{{ requestFeedbackDate }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="完成整改期限：">
              <span>{{ correctiveDeadline }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="督察员：">
              <span>{{ inspectors }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="督察部门：">
              <span>{{ issueDeptName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任部门：">
              <span>{{ dutyDeptName }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="问题描述：">
              <div v-if="problemDetail" style="border: 1px solid #ccc; width: 100%; min-height: 150px;">
                <Editor
                  style="height: auto; min-height: 150px; width: 100%;"
                  :modelValue="problemDetail"
                  :defaultConfig="viewEditorConfig"
                  mode="default"
                  @onCreated="handleViewEditorCreated"
                />
              </div>
              <span v-else>无</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="整改要求：">
              <span>{{ reformRequirement || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="规章制度依据：">
              <span>{{ basis || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <template v-if="['1', '2', '3', '4', '5', '6', '7'].includes(props.row?.reformStatus)">
        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="直接原因：">
              <span>{{ directCause || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="根本原因：">
              <span>{{ rootCause || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="纠正措施：">
              <span>{{ correctiveAction || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="预防措施：">
              <span>{{ precautionAction || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <template v-if="['1', '2', '4', '6', '7'].includes(props.row?.reformStatus)">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="措施制定人：">
              <span>{{ actionMakerName || '无' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="措施制定时间：">
              <span>{{ actionMakeTime || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <template v-if="['2', '3', '4', '6', '7'].includes(props.row?.reformStatus)">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="措施审核人：">
              <span>{{ actionEvalerName || '无' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="措施审核时间：">
              <span>{{ actionEvalTime || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="措施审核意见：">
              <span>{{ actionEval || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <div v-if="reformDetail && !detailLoading">
        <el-row :gutter="20" v-if="reformDetail.correctiveActionProof">
          <el-col :span="23">
            <el-form-item label="纠正措施整改证据：">
              <div style="border: 1px solid #ccc; width: 100%; min-height: 150px;">
                <Editor
                  style="height: auto; min-height: 150px; width: 100%;"
                  :modelValue="reformDetail.correctiveActionProof"
                  :defaultConfig="viewEditorConfig"
                  mode="default"
                  @onCreated="handleViewEditorCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="reformDetail.precautionActionProof">
          <el-col :span="23">
            <el-form-item label="预防措施整改证据：">
              <div style="border: 1px solid #ccc; width: 100%; min-height: 150px;">
                <Editor
                  style="height: auto; min-height: 150px; width: 100%;"
                  :modelValue="reformDetail.precautionActionProof"
                  :defaultConfig="viewEditorConfig"
                  mode="default"
                  @onCreated="handleViewEditorCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="reformDetail.oldCorrectiveActionProof">
          <el-col :span="23">
            <el-form-item label="历史纠正措施整改证据：">
              <div style="border: 1px solid #ccc; width: 100%; min-height: 150px;">
                <Editor
                  style="height: auto; min-height: 150px; width: 100%;"
                  :modelValue="reformDetail.oldCorrectiveActionProof"
                  :defaultConfig="viewEditorConfig"
                  mode="default"
                  @onCreated="handleViewEditorCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="reformDetail.oldPrecautionActionProof">
          <el-col :span="23">
            <el-form-item label="历史预防措施整改证据：">
              <div style="border: 1px solid #ccc; width: 100%; min-height: 150px;">
                <Editor
                  style="height: auto; min-height: 150px; width: 100%;"
                  :modelValue="reformDetail.oldPrecautionActionProof"
                  :defaultConfig="viewEditorConfig"
                  mode="default"
                  @onCreated="handleViewEditorCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <template v-if="['4', '6'].includes(props.row?.reformStatus)">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="整改效果审核人：">
              <span>{{ proofEvalerName || '无' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="整改效果审核时间：">
              <span>{{ proofEvalTime || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="整改效果审核意见：">
              <span>{{ rectificationOpinion || '无' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <template v-if="['4', '6', '7'].includes(props.row?.reformStatus)">
        <el-row :gutter="20">
          <el-col :span="23">
            <el-form-item label="整改实施审核结果：">
              <el-tag v-if="rectificationResult === '1'">整改通过</el-tag>
              <el-tag v-else-if="rectificationResult === '2'" type="danger">整改不通过-驳回纠正措施</el-tag>
              <el-tag v-else-if="rectificationResult === '3'" type="danger">整改不通过-驳回预防措施</el-tag>
              <el-tag v-else-if="rectificationResult === '4'" type="danger">整改不通过-驳回所有</el-tag>
              <el-tag v-else type="info">{{ rectificationResult }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

    </el-form>
  </v-dialog>
</template>

<style scoped>
/* Scoped styles can remain if needed */
</style>
